<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * CodeIgniter Model Class
 * @author	Gustavo  Delgado Rodriguez.
 * @version     1.0
 */
class Onecore_Controller extends CI_Controller {

    private static $instance;
    protected $_view;
    protected $_successAction;
    protected $_errorList = array();
    protected $_customResponse = array();
    protected $_moduleName;
    protected $_moduleDescription;
    protected $_modelInstance;

    /**
     * Constructor
     */
    public function __construct() {
        parent::__construct();
    }
    public function setSuccess($bool) {
        $this->_successAction = $bool;
    }
    public function getSuccess() {
        return $this->_successAction;
    }
    public function setErrorList($errorList) {
        $this->_errorList = $errorList;
    }
    public function getErrorList() {
        return $this->_errorList;
    }
    /*
     * Funcion que recibe un objeto con los campos que se desea buscar
     * ademas de un arreglo de condiciones. donde cada indice es el nombre
     * de la columna o atributo a condicionar
     *
     * $typeConditions = array('idTabla'=>'where','texto'=>'like')
     * $fields arreglo con lista de todas las columnas que tiene la tabla
     *
     */
    public function getConditionsByObject_old($obj, $typeConditions=null, $fields) {
        $conditions = array();
        foreach ($obj as $key => $value) {
            if (in_array($key, $fields) && $value !== '') {
                $conditions[] = array(
                    'field' => $key,
                    'value' => $value,
                    'type' => $typeConditions[$key]
                );
            }
        }
        return $conditions;
    }
    /*
     * Funcion que recibe un objeto con los campos que se desea buscar
     * ademas de un arreglo de condiciones. donde cada indice es el nombre
     * de la columna o atributo a condicionar
     *
     * $typeConditions = array('idTabla'=>'where','texto'=>'like')
     * $fields arreglo con lista de todas las columnas que tiene la tabla
     * $validate boolean que permite saber si es necesario validar cada campo con los existentes en la tabla
     * setear en FALSE cuando se haga join con distintas tablas. Ejem t1.t2_id = t2.id
     */
    public function getConditionsByObject($obj, $typeConditions=null, $fields, $validate=true) {
        $conditions = array();
        if($validate){
            foreach ($obj as $key => $value) {
                if (in_array($key, $fields) && $value !== '') {
                    $conditions[] = array(
                        'field' => $key,
                        'value' => $value,
                        'type' => $typeConditions[$key]
                    );
                }
            }
        }
        else{
            foreach ($obj as $key => $value) {
                $conditions[] = array(
                    'field' => $key,
                    'value' => $value,
                    'type' => 'where'
                );
            }
        }
        return $conditions;
    }
    public function loadGrid(){
        $conditions=array();
        $start = $this->input->post('start');
	$limit = $this->input->post('limit');

        $sort = $this->input->post('sort');
        $dir = $this->input->post('dir');

        $item = $this->input->post('item');

        if(!empty($item) && $item !== 'null'){
            $obj = json_decode($item);
            $fields = $this->_modelInstance->getFields();
            $conditionsFields = $this->_modelInstance->getFieldsConditions();
            $conditions = $this->getConditionsByObject($obj, $conditionsFields,$fields);
        }
        $order = null;
        if(!empty($sort) && $sort !== 'null'){
            $obj = json_decode($sort);
            $order = array(
                'field'=>$obj[0]->property,
                'direction'=>$obj[0]->direction
            );
        }

        $selected = array();
        $items = $this->_modelInstance->loadGrid($limit,$start,$conditions,$order,$selected);
        $data = array(
            'success'=>true,
            'results'=>$items['results'],
            'rows'=>$items['items'],
            //'sql'=>$this->db->last_query()
        );
        $this->layout->printLike(json_encode($data),'json');
    }
    function loadList($default=null){
        $conditions=array();
        $order = array();
        $selected = array();
        $item = $this->input->post('item');
        $defaultValues = array();
        if(!empty($item) && $item !== 'null'){
            $obj = json_decode($item);
            $fields = $this->_modelInstance->getFields();
            $conditionsFields = $this->_modelInstance->getFieldsConditions();
            $conditions = $this->getConditionsByObject($obj, $conditionsFields,$fields);
        }
        $items = $this->_modelInstance->loadList($order,$selected,$conditions,$default);
        $data = array(
            'success'=>true,
            'results'=>$items['results'],
            'rows'=>$items['items']
        );
        $this->layout->printLike(json_encode($data),'json');
    }
    function getItem(){
        $selected = array();
        $conditions = array();
        $item = $this->input->post('item');
        if(!empty($item) && $item !== ''){
            $obj = json_decode($item);
            $fields = $this->_modelInstance->getFields();
            $conditionsFields = $this->_modelInstance->getFieldsConditions();
            $conditions = $this->getConditionsByObject($obj, $conditionsFields,$fields);
        }
        
        $item = $this->_modelInstance->getItem($conditions,$selected);
        $data = array(
            'success'=>true,
            'data'=>$item
        );
        $this->layout->printLike(json_encode($data),'json');
    }

    /*
     * funcion que recive el arreglo de post $this->db->post() y el arreglo de todos los fields de la tablla, y valida
     * de que cada post sea un campo existente de la tabla
     */
    public function getInputsToSave($posts,$modelFields){
        $res = array();
        foreach ($posts as $key => $value) {
            if(in_array($key, $modelFields)){
                $res[$key] = $value;
            }
        }
        if(in_array('Log', $modelFields)){
            $res['Log'] = date('Y-m-d H:i:s');
        }
        elseif(in_array('FechaLog', $modelFields)){
            $res['FechaLog'] = date('Y-m-d H:i:s');
        }
        return $res;
    }
    /*
     * funcion que recive el arreglo de post $this->db->post() y el arreglo de todos los fields de la tablla,
     * retorna un arreglo con todos los campos que se ocupen en el filtro del update
     */
    public function getFilterFieldsToEdit($_posts,$modelFields){
        $res = array();
        foreach ($_posts as $key => $value) {
            if(strpos($key, '_')!==FALSE){
                $key = str_replace('_', '' , $key);
                if(in_array($key, $modelFields)){
                    $res[$key] = $value;
                }
            }
        }
        return $res;
    }
    public function objectToArray($obj){
        $arra= array();
        foreach ($obj as $key => $value) {
            $arra[$key] = $value;
        }
        return $arra;
    }
}
// END Controller class

/* End of file Controller.php */
/* Location: ./system/core/Controller.php */